/*
GANESHA - Reasoning on critical infrastructures affected by emergency situations
Copyright (c) 2010-2011, Information Eng. Research Unit - Univ. of Alcala
http://www.cc.uah.es/ie
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along
with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package es.uah.cc.ie.ganesha.sahana;

import es.uah.cc.ie.ganesha.GANESHAConfiguration;
import es.uah.cc.ie.ganesha.messaging.AlertMessage;
import es.uah.cc.ie.ganesha.nodes.NodeInfo;
import es.uah.cc.ie.ganesha.results.GANESHAResultEntry;
import es.uah.cc.ie.ganesha.results.GANESHAResults;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;

/**
 * Class that lets report to SAHANA the results obtained by GANESHA.
 * @author ieru
 */
public class SAHANAReport {

    /**
     * Sends GANESHA results to SAHANA Agasti
     * @param config GANESHA configuration, which indicates where is SAHANA
     * @param results GANESHA results to be sent.
     */
    public static void sendResultsToSAHANA(GANESHAConfiguration config, GANESHAResults results) {
        try {
            //Cargar clase de controlador de base de datos
            Class.forName((String) config.getParams().get("SAHANA_DB_DRIVER_PARAM"));
            //Crear el objeto de conexion a la base de datos
            Connection conexion = DriverManager.getConnection(
                    (String) config.getParams().get("SAHANA_DB_URI"),
                    (String) config.getParams().get("SAHANA_DB_USER"),
                    (String) config.getParams().get("SAHANA_DB_PWD"));

            //Crear objeto Statement para realizar queries a la base de datos
            Statement instruccion = conexion.createStatement();

            //Un objeto ResultSet, almacena los datos de resultados de una consulta
            for(GANESHAResultEntry<AlertMessage> entry : results.getPotentialIncidents().getIncidents())
            {
                String id = "GANESHA_" + Calendar.getInstance().getTimeInMillis();

                String description = "Nodes: [";
                for(NodeInfo node : entry.nodes)
                    description += node.getName() + "; ";
                
                description += "]";

                description = description.substring(0, Math.min(99, description.length()));
                String name = entry.message.getIdentifier().substring(0, Math.min(49, entry.message.getIdentifier().length()));

                instruccion.executeUpdate("INSERT INTO gis_feature (feature_uuid,poc_uuid,feature_coords) VALUES ('feature_" + id + "', 'poc_" + id + "','')");
                instruccion.executeUpdate("INSERT INTO gis_location (poc_uuid,location_id,opt_gis_mod,map_northing,map_easting,map_projection,gis_uid) VALUES ('poc_" + id + "','0',''," + entry.message.getCenterLongitude() +"," + entry.message.getCenterLatitude() + ",'','gis_" + id + "')");
                instruccion.executeUpdate("INSERT INTO gis_wiki (wiki_uuid,gis_uuid,name,description,opt_category,event_date,url,editable,author,approved) VALUES ('poc_" + id + "','0','" + name + "','" + description + "','gen',now(),'','1','GANESHA','1')");
                instruccion.executeUpdate("INSERT INTO gis_event_type (wiki_uuid,gis_uuid,event_type) VALUES ('poc_" + id + "','0','" + entry.message.getEventType() + "')");
            }

            conexion.close();
        } catch (ClassNotFoundException e) {
            System.out.println(e);
        } catch (SQLException e) {
            System.out.println(e);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
